package com.example.untils;

import com.example.exception.CustomException;
import org.apache.commons.beanutils.PropertyUtils;

public class BeanUtils {

    public static void copyPropertiesIgnoreCase(Object source, Object target) {
        try {
            for (java.beans.PropertyDescriptor targetPropertyDescriptor : java.beans.Introspector.getBeanInfo(target.getClass()).getPropertyDescriptors()) {
                String targetPropertyName = targetPropertyDescriptor.getName();
                for (java.beans.PropertyDescriptor sourcePropertyDescriptor : java.beans.Introspector.getBeanInfo(source.getClass()).getPropertyDescriptors()) {
                    String sourcePropertyName = sourcePropertyDescriptor.getName();
                    if (targetPropertyName.equalsIgnoreCase(sourcePropertyName)) {
                        // 检查源对象属性是否具有getter方法和目标对象属性是否具有setter方法
                        if (sourcePropertyDescriptor.getReadMethod() != null && targetPropertyDescriptor.getWriteMethod() != null) {
                            Object value = PropertyUtils.getProperty(source, sourcePropertyName);
                            PropertyUtils.setProperty(target, targetPropertyName, value);
                        }
                        break; //退出内部循环
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("500","BeanUtils报错");
        }
    }

    public static void simple(Object source) {
        try {
            for (java.beans.PropertyDescriptor sourcePropertyDescriptor :
                    java.beans.Introspector.getBeanInfo(source.getClass()).getPropertyDescriptors()) {
                String sourcePropertyName = sourcePropertyDescriptor.getName();
                Object value = PropertyUtils.getProperty(source, sourcePropertyName);

                PropertyUtils.setProperty(source, sourcePropertyName, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
